﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using eTerm.ASynClientSDK.Base;
using System.Text.RegularExpressions;

namespace eTerm.ASynClientSDK
{
    public sealed class QSCommand : ASyncPNCommand
    {
        private const string m_Command = @"QS SR";
        protected override ASyncResult ResultAdapter(string Msg)
        {
            QSResult Result = new QSResult();
            foreach (Match m in Regex.Matches(Msg, @"^\s{0,}(\d+)\.\s{0,}(([A-Z0-9]{2})(\d{1,}))\s+[A-Z]{1}\s{0,}([A-Z]{2}[0-9]{2}[A-Z]{3})\s+([A-Z]{6})\s+(([A-Z]{2})\d+)\s+(\d{4})[\+]?\s+(\d{4})[\+]?", RegexOptions.Multiline | RegexOptions.IgnoreCase))
            {
                Result.QSegments.Add(new QSegment()
                { 
                 getAirline=m.Groups[3].Value,
                 getCarrier = m.Groups[4].Value,
                  getOrgcity=m.Groups[6].Value.Substring(0,3),
                   getDstcity=m.Groups[6].Value.Substring(4),
                    getLink=m.Groups[8].Value,
                     getDeptime=m.Groups[9].Value,
                      getArridate=m.Groups[10].Value,
                       getDepdate=m.Groups[5].Value
                });
            }
            return Result;
        }

        public ASyncResult Execute() {
            ASyncResult result = base.GetSyncResult(m_Command);
            base.SendStream(@"QNE");
            return result;
        }

        protected override bool ExistNextPage(string msgBody)
        {
            bool flag = false;
            if (CurrentCmd == m_Command || CurrentCmd == @"QN")
            {
                PnCommand = @"PN";
                flag = Regex.IsMatch(msgBody.Trim(), @"\+$", RegexOptions.IgnoreCase | RegexOptions.Multiline);
            }
            else {
                Match m = Regex.Match(msgBody.Trim(), @"Q\s+EMPTY", RegexOptions.IgnoreCase | RegexOptions.Multiline);
                Match m1 = Regex.Match(msgBody.Trim(), @"\(\s+(\d{4})\s+\)\s+\(\s+(\d{4})\s+\)", RegexOptions.IgnoreCase | RegexOptions.Multiline);
                PnCommand = @"QN";
                flag = m.Success ? true : m1.Success ? m1.Groups[1].Value != "0000" : false;

            }
            //return Regex.IsMatch(msgBody.Trim(), @"\+$", RegexOptions.IgnoreCase | RegexOptions.Multiline);
            return flag;
        }
    }
}
